package com.lingjtx.iot.network.config;

import com.lingjtx.common.core.constant.MqConst;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.outbound.MqttPahoMessageHandler;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

/**
 * MQTT 发送端配置
 */
@Slf4j
@Order(2)
@Configuration
public class MqttPublisherConfig {

    private final MqttConfig mqttConfig;

    public MqttPublisherConfig(MqttConfig mqttConfig) {
        this.mqttConfig = mqttConfig;
    }

    @SneakyThrows
    @Bean
    public MqttPahoClientFactory publisherClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        factory.setConnectionOptions(mqttConfig.mqttConnectOptions());
        return factory;
    }

    @Bean
    public MessageChannel mqttPublisherChannel() {
        return new DirectChannel();
    }

    @Bean
    @ServiceActivator(inputChannel = "mqttPublisherChannel")
    public MessageHandler mqttPublisherHandle() {
        MqttPahoMessageHandler handler =
                new MqttPahoMessageHandler("publisher_" + mqttConfig.mqttClientId(),
                        publisherClientFactory());
        handler.setAsync(true);
        handler.setAsyncEvents(true); // 启用异步事件监听
        handler.setDefaultQos(mqttConfig.mqttProperties().getQos());
        handler.setDefaultTopic(MqConst.MqttSubscriberTopic.MQTT_TOPIC_LINGJTX);// 可以在发送消息时覆盖默认主题
        return handler;
    }
}
